<template>
  <div class="app-container ohn transaction-box">
    <div class="f22 pointer" @click="goBack()">
      【{{ testTrade.name }}】检测报价单
    </div>
    <el-divider class="mt50" content-position="left">基本信息</el-divider>
    <el-form
      ref="quotationCreateForm"
      v-loading="formLoading"
      class="mt36"
      :inline="true"
      :model="quotationCreateForm"
      status-icon
      :rules="rules"
      label-width="110px"
    >
      <el-form-item :label="'客户\nClient'" prop="client">
        <el-input
          v-model="quotationCreateForm.client"
          placeholder="请输入客户姓名"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'联络人\nAttn'" prop="attn">
        <el-input
          v-model="quotationCreateForm.attn"
          placeholder="请输入联络人"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'客户电话\nTel'" prop="telClient">
        <el-input
          v-model="quotationCreateForm.telClient"
          placeholder="请输入客户电话"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'客户传真\nFax'" prop="faxClient">
        <el-input
          v-model="quotationCreateForm.faxClient"
          placeholder="请输入客户传真"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'客户邮箱\nE-mail'" prop="email">
        <el-input
          v-model="quotationCreateForm.email"
          placeholder="请输入客户邮箱"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'发票抬头\nInvocie Title'" prop="invoiceTitle">
        <el-input
          v-model="quotationCreateForm.invoiceTitle"
          placeholder="请输入发票抬头"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'报价单编号\nQuotation No'" prop="quotationNum">
        <el-input
          v-model="quotationCreateForm.quotationNum"
          placeholder="请输入报价单编号"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'公司\nFrom'" prop="fromCom">
        <el-input
          v-model="quotationCreateForm.fromCom"
          placeholder="请输入公司名称"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'公司电话\nTel'" prop="telCom">
        <el-input
          v-model="quotationCreateForm.telCom"
          placeholder="请输入公司电话"
          clearable
          style="width: 240px"
        />
      </el-form-item>

      <el-form-item :label="'公司传真\nTel'" prop="faxCom">
        <el-input
          v-model="quotationCreateForm.faxCom"
          placeholder="请输入公司传真"
          clearable
          style="width: 240px"
        />
      </el-form-item>

      <el-form-item :label="'报价日期\nDate'" prop="gmtCreate">
        <el-date-picker
          v-model="quotationCreateForm.gmtCreate"
          type="date"
          placeholder="请选择报价日期"
          style="width: 240px"
        />
      </el-form-item>

      <el-form-item :label="'报告类型\nReport Type'" prop="reportType">
        <el-select
          v-model="quotationCreateForm.reportType"
          style="width: 240px"
          placeholder="请选择报告类型"
        >
          <el-option
            v-for="(item, index) in customerOptions"
            :key="item.key + index"
            :label="item.value"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        :label="'报告邮寄地址\nRe.delivery to'"
        prop="deliveryAddress"
      >
        <el-input
          v-model="quotationCreateForm.deliveryAddress"
          type="textarea"
          placeholder="请输入邮寄地址"
          :max-rows="3"
          maxlength="100"
          show-word-limit
          clearable
          style="width: 240px"
        />
      </el-form-item>

      <el-form-item :label="'测试周期\nTest period'" prop="testPeroid">
        <el-date-picker
          v-model="quotationCreateForm.testPeroid"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 240px"
          align="right"
        />
      </el-form-item>
      <el-divider class="mb36" content-position="left">费用信息</el-divider>
      <el-form-item :label="'报告费\nReport Fee'" prop="reportFee">
        <el-input
          v-model="quotationCreateForm.reportFee"
          placeholder="请填写报告费"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'快递费\n Express Fee'" prop="courierFee">
        <el-input
          v-model="quotationCreateForm.courierFee"
          placeholder="请填写快递费"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'税费\nTax Fee'" prop="taxFee">
        <el-input
          v-model="quotationCreateForm.taxFee"
          placeholder="请填写税费"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'折扣\n Discount'" prop="discount">
        <el-input
          v-model="quotationCreateForm.discount"
          placeholder="请填写折扣"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'总费用\nTatol Cost'" prop="totalCost">
        <el-input
          v-model="quotationCreateForm.totalCost"
          placeholder="请填写总费用"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'备注\nRemark'" prop="remark">
        <el-input
          v-model="quotationCreateForm.remark"
          type="textarea"
          placeholder="请填写备注"
          :rows="2"
          maxlength="100"
          show-word-limit
          clearable
          style="width: 240px"
        />
      </el-form-item>

      <el-divider class="mb36" content-position="left">账户信息</el-divider>
      <el-form-item :label="'户名\nAccount Name'" prop="bankAccountName">
        <el-input
          v-model="quotationCreateForm.bankAccountName"
          placeholder="请输入户名"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'账号\nBank Account'" prop="bankAccount">
        <el-input
          v-model="quotationCreateForm.bankAccount"
          placeholder="请输入账号"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'银行名称\nBank Name'" prop="bankName">
        <el-input
          v-model="quotationCreateForm.bankName"
          placeholder="请输入银行名称"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'公司签名\nClient.Sign'" prop="clientComSignature">
        <el-input
          v-model="quotationCreateForm.clientComSignature"
          placeholder="请输入公司签名"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item
        :label="'立标代表签名\nlibiaoRe.Sign'"
        prop="libiaoRepresentativeSignature"
      >
        <el-input
          v-model="quotationCreateForm.libiaoRepresentativeSignature"
          placeholder="请输入立标代表签名"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item :label="'盖章\nClient.Chop'" prop="clientComChop">
        <el-input
          v-model="quotationCreateForm.clientComChop"
          placeholder="请输入盖章"
          clearable
          style="width: 240px"
        />
      </el-form-item>

      <el-form-item :label="'审核人员\nAudit'" prop="audit">
        <el-input
          v-model="quotationCreateForm.audit"
          placeholder="请输入审核人员签名"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item
        :label="'客户签名日期\nClient Date'"
        prop="clientSignatureDate"
      >
        <el-date-picker
          v-model="quotationCreateForm.clientSignatureDate"
          type="date"
          placeholder="请选择客户签名日期"
          style="width: 240px"
        /> </el-form-item><el-form-item
        :label="'立标签名日期\nLibiao Date'"
        prop="libiaoSignatureDate"
      >
        <el-date-picker
          v-model="quotationCreateForm.libiaoSignatureDate"
          type="date"
          placeholder="请选择立标签名日期"
          style="width: 240px"
        />
      </el-form-item>

      <el-divider content-position="left">报价单明细</el-divider>

      <vxe-toolbar ref="xToolbar">
        <template #tools>
          <el-button
            type="primary"
            size="small"
            plain
            @click="insertEvent"
          >新增</el-button>
        </template>
      </vxe-toolbar>
      <vxe-table
        ref="xTable"
        border
        show-footer
        show-overflow
        class="editable-footer mb20"
        :merge-footer-items="mergeFooterItems"
        :row-config="{ isHover: true }"
        :export-config="{}"
        :footer-method="footerMethod"
        :footer-cell-class-name="footerCellClassName"
        :data="quotationCreateForm.testQuotationItemList"
        :edit-config="{ trigger: 'click', mode: 'row' }"
        @edit-closed="editClose"
      >
        <vxe-column type="seq" width="60" :title="'序号\nNum'" align="right" />
        <vxe-column
          field="reportNum"
          :title="'报告编号\nReport No'"
          :edit-render="{}"
        >
          <template #edit="{ row }">
            <vxe-input v-model="row.reportNum" type="text" />
          </template>
        </vxe-column>
        <vxe-column
          field="productDes"
          :title="'产品名称\nProduct Description'"
          :edit-render="{ autofocus: '.vxe-input--inner' }"
          width="160"
        >
          <template #edit="{ row }">
            <vxe-input
              v-model="row.productDes"
              type="text"
              :min="1"
              :max="120"
              @change="updateFooterEvent"
            />
          </template>
        </vxe-column>
        <vxe-column
          field="style"
          :title="'型号\nStyle/Item No'"
          :edit-render="{ autofocus: '.vxe-input--inner' }"
        >
          <template #edit="{ row }">
            <vxe-input
              v-model="row.style"
              type="text"
              @input="updateFooterEvent"
            />
          </template>
        </vxe-column>

        <vxe-column
          field="materialColor"
          :title="'材质/颜色\nMaterial/Color'"
          :edit-render="{ autofocus: '.vxe-input--inner' }"
        >
          <template #edit="{ row }">
            <vxe-input
              v-model="row.materialColor"
              type="text"
              @input="updateFooterEvent"
            />
          </template>
        </vxe-column>

        <vxe-column
          field="testItem"
          :title="'测试项目\nTest Item'"
          :edit-render="{ autofocus: '.vxe-input--inner' }"
        >
          <template #edit="{ row }">
            <vxe-input
              v-model="row.testItem"
              type="text"
              @input="updateFooterEvent"
            />
          </template>
        </vxe-column>
        <vxe-column
          field="unitPrice"
          :title="'单价\nUnit Price'"
          :edit-render="{ autofocus: '.vxe-input--inner' }"
        >
          <template #edit="{ row }">
            <vxe-input
              v-model="row.unitPrice"
              type="text"
              @input="updateFooterEvent"
            />
          </template>
        </vxe-column>
        <vxe-column
          field="qty"
          :title="'测试点数\nQty'"
          :edit-render="{ autofocus: '.vxe-input--inner' }"
        >
          <template #edit="{ row }">
            <vxe-input
              v-model="row.qty"
              type="text"
              @input="updateFooterEvent"
            />
          </template>
        </vxe-column>
        <vxe-column
          field="amountRmb"
          :title="'测试金额\nAmount/RMB'"
          :edit-render="{ autofocus: '.vxe-input--inner' }"
        >
          <template #edit="{ row }">
            <vxe-input
              v-model="row.amountRmb"
              type="text"
              @input="updateFooterEvent"
            />
          </template>
        </vxe-column>
        <vxe-column title="操作" width="80">
          <template #default="{ row }">
            <el-button
              type="text"
              status="primary"
              @click="deleteEvent(row)"
            >删除</el-button>
          </template>
        </vxe-column>
      </vxe-table>

      <el-form-item>
        <div class="tr">
          <el-button
            v-loading="formLoading"
            type="primary"
            @click="submitForm('quotationCreateForm')"
          >保存</el-button>
          <el-button @click="resetForm('quotationCreateForm')">重置</el-button>
        </div>
      </el-form-item>
    </el-form>

    <el-divider content-position="left">备注</el-divider>
    <div class="remark-content">
      <div class="fb">注意 Remark：</div>
      <p>
        1.
        在我方按照经客户确认过的信息颁发报告后。如客户有修改要求，我方将按照RMB
        100 元/次的标准收取报告修改费。
      </p>
      <p>
        2. 样品开案之前需 100%
        全款到帐，以收到付款凭证为准。如有延迟，我方将顺期延迟发送检测报告！
      </p>
      <p>
        3. 开案必备条件<span
          class="fb"
        >（特别提醒：因提交以下资料滞后而影响测试周期的，责任由客户自己承担）</span>。<br>
        a. 送样要求：样品量应满足测试所需。<br>
        b. 回签确认该报价单。<br>
        c. 提交确认、签字了的测试申请单。
      </p>
      <p>
        4.
        该报价自生效之日起一个月内有效，一个月后未开始测试的或未被申请退回的样品会被自动处理掉。
      </p>
      <p>
        5.
        当仅依据产品图片或测试相关资料进行报价的，报价和测试周期仅供参考，最终需以实际收到样品后确定的报价及测试周期为准。
      </p>
      <p>6. 上述部分项目可能会分包至我们的分包实验室进行测试。</p>
      <p>
        7. 本公司对测试报告只承担被证实的过失责任，并且赔偿金额不超过测试费用的
        5 倍。
      </p>
      <p>
        8.
        报告语言：如需出具英文报告，请提供相关的英文信息（如公司抬头，地址，样品及其零部件的名称），若在确认报价单前未能提供，我司将默认为自行翻译。届时若因翻译问题而需修改报告，我司将须收取报告修改费用。
      </p>
      <p>9. 报告方式：如需提供纸质报告，我方将收取RMB 100元/份的纸质报告</p>
    </div>
  </div>
</template>

<script>
import methods from "./pub_methods/validate"
export default {
  data() {
    return {
      formLoading: false,
      testTrade: {
        name: "",
        id: "",
        status: ""
      },
      rules: methods.quotationCreateValidate,
      quotationCreateForm: {
        testTradeId: "",
        client: "北京烤鸭店",
        quotationNum: "BJKY001",
        attn: "厨师老张",
        fromCom: "立标检测",
        telClient: "15769321569",
        telCom: "13526985623",
        faxClient: "abcd",
        faxCom: "efgh",
        email: "xxx@153.com",
        gmtCreate: "2022-01-31 23:10:12",
        invoiceTitle: "检测烤鸭的抬头",
        reportType: "中文电子档",
        deliveryAddress: "北京市通州区北京烤鸭店",
        testPeroid: ["2022-01-31 23:10:12", "2022-06-31 23:10:12"],
        bankAccountName: "bjduck",
        bankAccount: "622848111",
        bankName: "农业银行",
        clientComSignature: "烤鸭老王",
        libiaoRepresentativeSignature: "立标老水",
        clientComChop: "x3333",
        audit: "y3333",
        clientSignatureDate: "2022-01-31 23:10:12",
        libiaoSignatureDate: "2022-01-31 23:10:12",
        customer: "",
        remark: "备足",
        reportFee: "1元",
        courierFee: "2元",
        taxFee: "3元",
        discount: "75折",
        totalCost: "100块",
        testQuotationItemList: [
          {
            reportNum: "01",
            productDes: "烤鸭皮",
            style: "肉类",
            materialColor: "金黄",
            testItem: "烤鸭皮脆不脆",
            unitPrice: "100",
            qty: "10",
            amountRmb: "1000"
          },
          {
            reportNum: "02",
            productDes: "烤鸭肉",
            style: "肉类",
            materialColor: "金黄",
            testItem: "烤鸭肉香不香",
            unitPrice: "200",
            qty: "3",
            amountRmb: "600"
          }
        ]
      },
      mergeFooterItems: [
        // { row: 0, col: 0, rowspan: 0, colspan: 8 },
        { row: 0, col: 1, rowspan: 9, colspan: 9 }
      ],
      customerOptions: [
        { key: 1, value: "中文纸质档" },
        { key: 2, value: "中文电子档" },
        { key: 3, value: "英文电子档" },
        { key: 4, value: "英文纸质档" }
      ],
      allowAdd: true
    }
  },
  created() {
    this.testTrade.name = this.$route.query.name
    this.testTrade.id = this.$route.query.id
    this.testTrade.status = this.$route.query.status
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.quotationCreateForm.testTradeId = this.testTrade.id
          const insertData = this.$refs.xTable.getRecordset()
          this.quotationCreateForm.testQuotationItemList =
            insertData.insertRecords
          if (this.quotationCreateForm.testQuotationItemList.length === 0) {
            this.$message.warning("请填写报价单明细")
          } else {
            this.formLoading = true
            this.$store
              .dispatch(
                "transaction/saveTestQuotation",
                this.quotationCreateForm
              )
              .then((res) => {
                const { data, success, errorMessage } = res
                if (success) {
                  this.$refs[formName].resetFields()
                  this.$message.success(data.msg)
                } else {
                  this.$message.error(errorMessage)
                }
              })
              .catch(() => {})
              .finally(() => {
                this.formLoading = false
              })
          }
        } else {
          console.log("error submit!!")
          return false
        }
      })
    },
    resetForm(formName) {
      this.quotationCreateForm.testQuotationItemList = []
      this.$refs[formName].resetFields()
    },
    goBack() {
      this.$router.push({
        path: "/detection/list"
      })
    },
    footerCellClassName({ $rowIndex, columnIndex }) {
      if (columnIndex === 1) {
        if ($rowIndex === 0) {
          return "col-blue"
        }
      }
      if (columnIndex === 2) {
        if ($rowIndex === 1) {
          return "col-red"
        }
      }
    },
    // 在值发生改变时更新表尾合计
    updateFooterEvent() {
      const $table = this.$refs.xTable
      $table.updateFooter()
    },
    meanNum(list, field) {
      let count = 0
      list.forEach((item) => {
        count += Number(item[field])
      })
      return count / list.length
    },
    sumNum(list, field) {
      let count = 0
      list.forEach((item) => {
        count += Number(item[field])
      })
      this.quotationCreateForm.totalCost = count
      return count
    },
    footerMethod({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return "总金额："
          }
          if (["amountRmb"].includes(column.property)) {
            return this.sumNum(data, column.property) + "元"
          }
          return null
        })
      ]
    },
    async insertEvent(row) {
      if (this.allowAdd) {
        const record = {
          testQuotationId: undefined,
          reportNum: "",
          productDes: "",
          style: "",
          materialColor: "",
          testItem: "",
          unitPrice: "",
          qty: "",
          amountRmb: "6"
        }
        const { row: newRow } = await this.$refs.xTable.insert(record, row)
        console.log(newRow)
        await this.$refs.xTable.setActiveCell(newRow, "productDes")
      }
    },
    // 编辑单元格事件
    async editClose({
      row,
      rowIndex,
      $rowIndex,
      column,
      columnIndex,
      $columnIndex
    }) {
      const errMap = await this.$refs.xTable
        .validate(true)
        .catch((errMap) => errMap)
      if (errMap) {
        this.allowAdd = false
      } else {
        this.allowAdd = true
      }
    },
    deleteEvent(row) {
      this.$confirm("您确定要删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$refs.xTable.remove(row)
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          })
        })
    }
  }
}; -9
</script>
<style lang="scss" scoped>
.transaction-box {
  .el-form .el-form-item__label {
    background-color: red;
    line-height: 20px !important;
  }
  .el-form-item--medium .el-form-item__label {
    line-height: 20px !important;
  }
  .remark-content {
    font-size: 12px;
    color: #808080;
    line-height: 20px;
  }
}
</style>
